package com.twu.biblioteca;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Created by abhishekpuri on 10/7/14.
 */
public class Catalog<T> {
    private Collection<T> items;
    private IOHandler ioHandler;

    public Catalog()
    {
        items = new ArrayList<T>();
        ioHandler = new IOHandler();
    }
    public Catalog(Collection<T> itemList)
    {
        items = itemList;
        ioHandler = new IOHandler();
    }

    public void printItemList()
    {
        int i=1;
        for(T item: items) {
            try{
                ioHandler.printlnToConsole(i++ + ". " + item.getClass().getMethod("getSummary").invoke(item));
            }
            catch (Exception ex)
            {
                ioHandler.printToErrorLog("BibAppErr : "+ex.getMessage());
            }
        }
    }

    private T searchItem(T item) {
        for(T curItem: items) {
            if (curItem.equals(item)) {
                return curItem;
            }
        }
        return null;
    }

    public T searchItemByName(String name) {
        for(T item: items) {
            try {
                if (item.getClass().getMethod("getName").invoke(item).equals(name)) {
                    return item;
                }
            }
            catch (Exception ex) {
                ioHandler.printToErrorLog("BibAppErr : "+ex.getMessage());
            }
        }
        return null;
    }

    public boolean addItemToCatalog(T item) {
        if(searchItem(item)==null) {
            items.add(item);
            return true;
        }
        else {
            ioHandler.printlnToConsole(item.getClass().getSimpleName() + " already present in catalog");
            return false;
        }
    }

    public boolean deleteItemFromCatalog(T item) {
        T res= searchItem(item);
        if(res!=null) {
            items.remove(res);
            return true;
        }
        else {
            ioHandler.printlnToConsole(item.getClass().getSimpleName() + " not present in the catalog");
            return false;
        }
    }
}

